import json
HOST = 'localhost'
PORT = 6546

def print_info_msg(msg):
	spit_json(msg)

def pretty_print_status(msg):
	print('\nTURN:', msg.get('turn'), '\n')
	for i, row in enumerate(msg.get('board')):
		print(i + 1, ':', end='')
		for card in row:
			print(' %3d' % (card,), end='')
		print('')
	print('Your hand:', end='')
	for card in msg.get('hand'):
		print(' %3d' % (card,), end='')
	print('')

def print_query_msg(msg):
	if msg.get('action') == 'give_card':
		pretty_print_status(msg)
	else:
		spit_json(msg)

def spit_json(msg):
	for k, v in msg.items():
		print(k, v)

def parse_server_message2(jmsg):
	try:
		typ = jmsg.get('type')
	except:
		print('unable to get type')
		exit(8)
	return typ

def parse_server_message(jmsg):
	typ = jmsg.get('type')
	if typ == 'info':
		print_info_msg(jmsg)
	elif typ == 'query':
		print_query_msg(jmsg)
	else:
		print('unknown message type:', typ)
	return typ

def send_msg(ssock,msg):
	jmsg = json.dumps(msg)
	print('msg to send:', jmsg)
	ssock.send(bytes(jmsg, 'utf-8'))

def print_not_implemented():
	print('not_implemented')

def process_info(msg):
	print_not_implemented()

def process_query(msg):
	print_not_implemented()

def build_action(action, rest = {}):
	ret = { 'action': action}
	ret.update(rest)

	return ret

def start_game():
	return build_action('start')

def choose_row(row_index):
	return build_action('select_row', { 'i': row_index })

def set_name(name):
	return build_action('set_name', { 'name': name })

def give_card(card):
	return build_action('give_card', { 'card': card })

def get_action(jmsg):
	try:
		action = jmsg.get('action')
	except:
		print('unable to get action')
		exit(8)
	return action